﻿using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using BuildServer.Models;

namespace BuildServer.Controllers
{
    [Authorize]
    public class PropertiesController : Controller
    {
        private BuildServerDbContext db = new BuildServerDbContext();

        //
        // GET: /Properties/Edit/5

        public ActionResult Edit(int id = 0)
        {
            var dbset = db.BuildDefinitions.Include(x => x.BuildTemplate).Include(x => x.BuildProperties);
            BuildDefinition builddefinition = dbset.FirstOrDefault(x => x.Id == id);
            if (builddefinition == null)
            {
                return HttpNotFound();
            }

            EditPropertyModel model = new EditPropertyModel(builddefinition);
            return View(model);
        }

        //
        // POST: /Properties/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditPropertyModel model)
        {
            var dbset = db.BuildDefinitions.Include(x => x.BuildProperties);
            BuildDefinition builddefinition = dbset.FirstOrDefault(x => x.Id == model.id);
            if (builddefinition == null)
            {
                return HttpNotFound();
            }

            // remove obsolete properties
            foreach (var item in builddefinition.BuildProperties.Where(x => !model.Properties.Any(y => x.Name == y.Name)).ToList())
            {
                db.BuildProperties.Remove(item);
            }

            // update properties
            foreach (var item in model.Properties)
            {
                builddefinition.SetBuildProperty(item.Name, item.Value);
            }
            db.SaveChanges();
            return RedirectToAction("Index", "Definition");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
